import React, { useCallback, useEffect, useState } from "react";
import styles from "./style.module.scss";
import { withService } from "../../lib/AppView";
import { Form } from "../../lib";
import { Spin } from "antd";

interface IInputBoxProps {
    icon: React.ReactNode;
    label: string|React.ReactNode;
    placeholder?: string;
    type?: "text"|"password";
    children?: React.ReactNode;
    name: string;
    onChange?: (value: any) => void;
}

export const InputBox = ({ icon, label, placeholder, type, children, onChange, name }: IInputBoxProps) => {
    const [ inputBoxType ] = useState(type ?? "text");
    return (<label className={styles.inputBox}>
        <i>{icon}</i>
        <div>
            <Form.Item name={name}>
                <input type={inputBoxType} placeholder={placeholder} onChange={(event) => typeof onChange === "function" && onChange(event.target.value)}/>
            </Form.Item>
            <span className={styles.inputBoxLabel}>{label}</span>
            {children}
        </div>
    </label>);
};

export const VerifyCode = withService()((props) => {
    const [ imgUrl ] = useState(() => props.withServiceApi.getUrl("login.captchaGenerate") as any);
    const [ verifyImg, setVerifyImg ] = useState<string>();
    const [ canvas ] = useState(() => document.createElement("canvas"));
    const [ canvasContext ] = useState(() => canvas.getContext("2d"));
    const updateImg = useCallback(() => {
        const img = new Image();
        const timestamp = new Date().getTime();
        props.withServiceApi.send({
            endPoint: "login.captchaGenerate",
            uri: {
                timestamp
            },
            header: {
                "Content-Type": "image/jpeg"
            }
        }).then((resp: any) => {
            const fileReader = new FileReader();
            fileReader.onload = () => {
                setVerifyImg(fileReader.result as string)
            };
            fileReader.onerror = () => {
                setTimeout(() => updateImg(), 1000);
            }
            fileReader.readAsDataURL(resp);
        }).catch((err) => {
            console.error(err);
            setTimeout(() => updateImg(), 2000);
        });
    },[imgUrl]);
    useEffect(()=> {
        canvas.setAttribute("style", "position: absolute;left:0;top:0;z-index: -2");
        document.body.appendChild(canvas);
        updateImg();
        return () => {
            document.body.removeChild(canvas);
        };
    }, []);
    return (<>
        { verifyImg && <img
            className={styles.verifyCode}
            src={verifyImg}
            onClick={() => {
                updateImg();
            }}
        />}
        { !verifyImg && <Spin className={styles.verifyCodeLoading}/> }
    </>);
});